<?


// function needed to get only the site name out of a -maybe- complex URL
function get_url($url)
	{
	$result=explode("/",$url);
	if ( $result[2] <> "" )
			{
			$return = $result[2];
			}
	else
			{
			$return = $result[0];
			}
	return $return;
	}

//used for admin to log in. in-password, out-redirect
function login_editor($login_name,$password)
	{
	
	$query_txt="SELECT * FROM editors WHERE login_name='$login_name' AND password='".md5($password)."' AND valid = '1' ";
	$query=mysql_query($query_txt);
	
	$rows=mysql_num_rows($query);
	
	if ( $rows == 1 )
		{
		$_SESSION['LOGIN_NAME_EDITOR'] = $login_name ;
		header("Location: index.php");
		exit();
		}
	else	return 0;
	}






//////////////////////////////////////////////
function next_back_button_new( $index, $select, $block, $nr_per_page ){
        global $tpl;
        $inDB=mysql_query($select);
                $nr_problems=mysql_num_rows($inDB);//we find the total nr of recordings
                if( $nr_problems == 0 ){//return 0
                        return 0;
                }

//                if( $nr_problems <= $nr_per_page ){//dont do anything else if there are no more than one page reesults
//                        return $select;
//                }

                if(!isset($index)) //we initialize $index
                        {
                                $index=0;
                                $next=$index+1;
                        }


                $next=$index+1;
                $prew=$index-1;

        if ( $prew*$nr_per_page >= 0 )//we only display the left arrow if there are results
                {
                $tpl->assign("prew",$prew);
                $tpl->assign("next_word","Next");
                }

        if( $next*$nr_per_page < $nr_problems)//we only display the right arrow if there are results
                {
                $tpl->assign("next",$next);
                $tpl->assign("back_word","Prev");
                }
				if 	( $index==0  )
				{
					$next=1;
					$tpl->assign("next",$next);
					$tpl->assign("back_word","Prev");
				}


                $pages=floor($nr_problems/$nr_per_page);
                $cont=0;
                //echo $pages;
                for($i=0;$i < $pages;$i++)
                        {
                        $tpl->assign("nr",$i+1);
                        $tpl->assign("nr_real",$i);
                        $tpl->assign("href","archives.php");
                        if ($i!=$index){
                                $tpl->parse($block.".central.nr_pagina.nuindex_ahref");
                                $tpl->parse($block.".central.nr_pagina.nuindex_slasha");
                                $tpl->parse($block.".central1.nr_pagina.nuindex_ahref");
                                $tpl->parse($block.".central1.nr_pagina.nuindex_slasha");
                        }
                        else {
                                $tpl->parse($block.".central.nr_pagina.daindex_start");
                                $tpl->parse($block.".central.nr_pagina.daindex_end");
                                $tpl->parse($block.".central1.nr_pagina.daindex_start");
                                $tpl->parse($block.".central1.nr_pagina.daindex_end");
                        }
                        $tpl->parse($block.".central.nr_pagina");
                        $tpl->parse($block.".central1.nr_pagina");

                        if( $i == $pages-1 && $nr_problems%$nr_per_page != 0 && $cont == 0 ){
                                $pages=$pages+1;
                                $cont=1;
                        }

                        }


                $tpl->parse($block.".central");
                $tpl->parse($block.".central1");

                $next=$index+1;
                $prew=$index-1;
                if ($index > 0)
								{
									$tmp_index=$index-1;
									$list_index_problems=$select." LIMIT ".($tmp_index*$nr_per_page).", $nr_per_page";
								}
								else
								{
									$list_index_problems=$select." LIMIT ".($index*$nr_per_page).", $nr_per_page";
								}
                $tpl->assign("selected_index", $index);
                //echo "aici";                
        return $list_index_problems;



}

//logout for editors. in/out -nothing.
function logout_editors()
        {
        $_SESSION['LOGIN_NAME_EDITOR'] = "";
        }
                                                                                                   

//used for admin to log in. in-password, out-redirect
function login_admin($password)
        {
        global $ADMIN_PASSWORD;
                                                                                            
        if ( $password == $ADMIN_PASSWORD )
                        {
                        $_SESSION['LOGIN_NAME'] = "admin";
                        header("Location: index.php");
                        }
                                                                                            
        }
	
//logout for admin. in/out -nothing.
function logout_admin()
	{
	$_SESSION['LOGIN_NAME'] = "";
	}

		                                                                                            
//we check whether a string is an email address or not. in-> email, out 1 for ok , 0 for not_email	                                                                                                              
function check_email($email)
{
if ( $email != '' )
        if ( preg_match("/([a-z0-9\.\-_])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", $email)  )
                return 1;
        else    return 0;
}

//send an email to user/editor with his new password.
//IN-> ID USER & table ( users or editors), OUT-> ok or error (1 or 0)

function send_email_with_pass($id,$table,$new_password)
	{
	global $NEW_PASS_MESSAGE,$FROM_NAME,$FROM_EMAIL;
	
	$query_txt="SELECT * FROM $table where id='$id' ";
	$query=mysql_query($query_txt);
	
	$line=mysql_fetch_array($query);
	$email_message=str_replace("USER_NAME",$line['user_name'],$NEW_PASS_MESSAGE);
	$email_message=str_replace("LOGIN_NAME",$line['login_name'],$email_message);
	$email_message=str_replace("EMAIL_ADDRESS",$line['email'],$email_message);
	$email_message=str_replace("NEW_PASSWORD",$new_password,$email_message);
	
	$mail = new PHPMailer();
                                                                                                                                                             
	$mail->IsSMTP(); // telling the class to use SMTP
	$mail->IsHTML(true);
    $mail->WordWrap = 80;
                             
	$SITE_NAME=display_system_messages(3);
	$FROM_NAME=display_system_messages(4);
	$FROM_EMAIL=display_system_messages(5);

	                                                                                                                                
    $mail->From     = display_system_messages(4);
    $mail->FromName = display_system_messages(3);
    $mail->Subject  = display_system_messages(6);
                                                                                                                                                             
    //HTML mail
    $mail->Body    = nl2br($email_message);
    //plain text mail
    $mail->AltBody = $email_message;
                                                                                                                                                             
    $mail->Host     = "192.168.1.2";
    $mail->Mailer   = "sendmail";
                                                                                                                                                             
    $mail->AddAddress($line['email'], $line['user_name']);
                                                                                                                                                             
    if(!$mail->Send())      $result=0;
    else                    $result=1;
                                                                                                                                                             
    // Clear all address
    $mail->ClearAddresses();
                                                                                                                                                             
	return($result);
	
	}
	
	
	
 //function used to generate a new password for a certain user. 
 //the user will  be informed about this changed by email
 //in: id user. out: 0=error,1=succcess
 function generate_new_pass($id,$table)
 	{
	$out=0;
	$new_pass=rand(100,999)."-".rand(100,999)."-".rand(100,999);
	$new_md5_pass=md5($new_pass);
	
	$query_txt="UPDATE $table SET password='$new_md5_pass' where id='$id' ";
	$query_valid="SELECT * FROM $table WHERE id='$id' ";
	$query=mysql_query($query_valid);
	
	if ( mysql_num_rows($query)  == 1 )
		{
		if ( mysql_query($query_txt) == 1 )		$out=1;
		
		//we send an email to this user
		send_email_with_pass($id,$table,$new_pass);
		}
	return($out);
	}

		
		
		
//function for alternating colors. in : one color name ( css class actually) ;out : nothing 
// do remember that we use what is defined in .css as alternate colours for color1&2	
function alternate_colors($color = "text_gray")
	{
	global $tpl;
	$color1="text_white";
	$color2="text_gray";
	
	$color == $color1 ? $color = $color2 : $color = $color1;
	$tpl->assign("color",$color);
	return($color);
	}

			

 function display_system_messages($id_message)
	{
		$query="select messages.message from messages,languages "
				."where messages.id_message='$id_message' and "
				."messages.id_language=languages.id and "
				."languages.language='".$_SESSION['LANGUAGE']."'";
		$result=mysql_query($query);
		if (1 <> mysql_num_rows($result)){
			return "$query";
		}
		else {
			$rez=mysql_fetch_array($result);
			return $rez['message'];
		}

	}

function date_transform($date_init)		
{
	$date_hour=substr($date_init,10,2);
	$date_minute=substr($date_init,13,2);
	$date_second=substr($date_init,16,2);
	$date_day=substr($date_init,7,2);
	$date_month=substr($date_init,5,2);
	$date_year=substr($date_init,0,4);
	return(mktime($date_hour,$date_minute,$date_second,$date_month,$date_day,$date_year));
}






function get_incoming_url($HTTP_REF)
{	
	$urltab=explode("/",$HTTP_REF);
	$incoming_url=$urltab[2];
		
	$SQLselect="SELECT * FROM url_address WHERE url='".$incoming_url."'";//we look for an incoming url in our tabel url_address	
	$SQLsel=mysql_query($SQLselect);

	
	if( mysql_num_rows($SQLsel) == 0 )//if we don`t find it in out DB...
		{
		$query_insert_url="insert into url_address(`url`) values('".$incoming_url."')";
		mysql_query($query_insert_url);	
		#echo "echo 1".$query_insert_url;
			
		$SQLselect="SELECT * FROM incoming_links WHERE url='".$incoming_url."'";
		$SQLinsert=mysql_query($SQLselect);	
					
		if(mysql_num_rows($SQLinsert) == 0 )
			{		
			$query_insert_url="insert into incoming_links(`url`, `incoming_views`, `new_views`) values('".$incoming_url."' , 1,1)";
			mysql_query($query_insert_url);	
			#echo "echo 2: $query_insert_url";		
			}
		else
			{
			$query_update_url="UPDATE incoming_links set incoming_views=incoming_views+1, new_views=new_views+1 where url='".$incoming_url."'";
			mysql_query($query_update_url);
			#echo "echo 3 $query_update_url";				
			}						
		}
	else//if we find it...
		{
		$SQLselect="SELECT * FROM incoming_links WHERE url='".$incoming_url."'";	
		$SQLinsert=mysql_query($SQLselect);	
		if(mysql_num_rows($SQLinsert) == 0 )
			{		
			$query_insert_url="insert into incoming_links(`url`, `incoming_views`, `new_views`) values('".$incoming_url."' , 1,1)";
			mysql_query($query_insert_url);
			#echo "echo 4 $query_insert_url";			
			}
		else
			{
			$query_update_url="UPDATE incoming_links set incoming_views=incoming_views+1, new_views=new_views+1 where url='".$incoming_url."'";
			mysql_query($query_update_url);
			#echo "echo 5 $query_update_url";				
			}	
		}	
								
}

function updateHitsIn() {
	
	$ref = false;
	if (preg_match('/http:\/\/(www)?[a-z0-9_.-]*\b([a-z0-9_-]+\.[a-z]{2,4})\/?/', $_SERVER['HTTP_REFERER'], $match)) {
		$ref = $match[2];
	}
	
	$ip = $_SERVER['REMOTE_ADDR'];
	$timenow = time();

	if ($ref !== false && $ref <> '') {
		$query = "SELECT id FROM domains_stats WHERE domain LIKE '%$ref'";

		if (mysql_num_rows(mysql_query($query))) {
			
			$query = "SELECT id FROM in_domains_ip WHERE ip = '$ip'";
			
			if (! mysql_num_rows(mysql_query($query))) {
				
				$query = "INSERT INTO in_domains_ip VALUES('', '$timenow', '$ip')";
				mysql_query($query);
				
				$query = "UPDATE domains_stats SET hits_in = (hits_in + 1), credits = ( (hits_in + 1) * ".TRADE_RATIO." - hits_out ) WHERE domain LIKE '%$ref'";
				mysql_query($query);
	//testing
	//$query = "INSERT INTO test VALUES('', '".$_SERVER['HTTP_REFERER']."', '$ref', '".$_SERVER['REMOTE_ADDR']."')";
	//mysql_query($query);
	//testing
			}
		}	
	}
}

function updateHitsOut($url) {

	preg_match('/http:\/\/(www)?[a-z0-9_.-]*\b([a-z0-9_-]+\.[a-z]{2,4})\/?/', $url, $match);
	$url = $match[2];
	$ip = $_SERVER['REMOTE_ADDR'];
	$timenow = time();

	$query = "SELECT domain FROM domains_stats WHERE domain LIKE '%$url'";
	
	if (mysql_num_rows(mysql_query($query))) {

		$query = "SELECT ip FROM out_domains_ip WHERE domain = '$url' and ip = '$ip'";
		
		if (! mysql_num_rows(mysql_query($query))) {
			
			$query = "UPDATE domains_stats SET hits_out = (hits_out + 1), credits = ( hits_in * ".TRADE_RATIO." - (hits_out + 1) ) WHERE domain LIKE '%$url'";
			mysql_query($query);
			
			$query = "INSERT INTO out_domains_ip VALUES('', '$url', '$ip', '$timenow')";
			mysql_query($query);
		}
	}
}

function displayTradingLinks($limit = false, $rand = true) {

	$query = "SELECT domain FROM domains_stats WHERE credits > '0'";
	
	if ($rand) {
		$query .= " ORDER BY RAND()";
	}
	if ($limit) {
		$query .= " LIMIT ".$limit;
	}

	$res = mysql_query($query);
	while ($row = mysql_fetch_row($res)) {
		$ret[] = $row[0];
	}
	
	return $ret;
}

function format_table($head, $data){

	$posindex = 1;
		
	$color1 = "#F6F6F6";
	$color2 = "#FFFFFF";
	$row_count = 0;
	
	$table = "
				<table cellspacing=\"1\" cellpadding=\"3\" style=\"font-size: 15px\">
					<tr bgcolor=\"#e0e0e0\">
				";
				
	foreach ($head as $hval) {
		$table .= "<td width=\"20\">".$hval.
					"</td>";
	}
	$table .= "</tr>";
	
	foreach ($data as $row){
		
		$row_color = ($row_count % 2) ? $color1 : $color2;
	
		$table .= "<tr>
						<td bgcolor=\"$row_color\" align=\"center\">" . $posindex++ . "
						</td>";
		
		foreach ($row as $val){
			
			$table .= "
						<td bgcolor=\"$row_color\">" . $val . "
						</td>";

		}
		echo "</tr>";
		$row_count++;
	}
	
	$table .= "</table>";
	return $table;
}

/**
 * include un modul
 * - cod eroare 1: nu exista un director pentru acest modul
 * @param string $modul
 * @return true - daca modulul a fost incarcat cu succes, false altfel
 */
function includeModule($module){
    if($module == ""){
        throw  new Exception('Numele modulului nu este corect');
    }
    $modulePath = "modules/$module";    
    if(is_dir($modulePath)){        
        if(file_exists("$modulePath/index.php")){
            if(file_exists("$modulePath/defines.php")){
                require_once "$modulePath/defines.php";
            }
            if(file_exists("$modulePath/common.php")){
                require_once "$modulePath/common.php";
            }
            require_once "$modulePath/index.php";
           
        } else {
            throw  new Exception("Modulul $module nu are un fisier index.php");
        }
    } else {
        throw  new Exception("Modulul $module nu exista",1);

    }
    
}

/**
 * poerneste un modul
 * @param string $module
 */
function runModule($module){    
    if($module == ""){
        throw  new Exception('Numele modulului nu este corect');
    }
   $query = "SELECT * FROM `modules` WHERE moduleName LIKE '{$module}' LIMIT 1";
   $result = mysql_query($query);
    if(mysql_num_rows($result) != 1){
        throw  new Exception("Modulul <b>$module</b> nu se afla in baza de date");
    }
    try {
        includeModule($module);
        if(function_exists('execute')){
            call_user_func('execute', 'action');
        }
    } catch (Exception $e){
        //cod 1: nu exista un director cu numele modulului
        if($e->getCode() != 1){
            throw  $e;
        } else {
            //modulul exista doar in baza de date
            $moduleData = mysql_fetch_assoc($result);  
            displayStaticModuleContent($moduleData);
        }
    }
}

/**
 * afiseaza un modul cu continut static
 * @param array module - datele modulului
 * 
 */
function displayStaticModuleContent(&$moduleData){
    $tpl = XTemplate::getInstance();    
    $tpl->assign_file('CONTENT','static_module.html');
    $tpl->assign('moduleContent', $moduleData['moduleContent']);
    $tpl->assign('moduleName', $moduleData['moduleName']);
    $tpl->assign('metaTitle', $moduleData['moduleTitle']);
    $tpl->parse('main.metaTitle');
    $tpl->assign('metaKeywords', $moduleData['moduleMetaKeywords']);
    $tpl->parse('main.metaKeywords');
    $tpl->assign('metaDescription', $moduleData['moduleMetaDescription']);
    $tpl->parse('main.metaDesccription');
    $tpl->assign('moduleTitle',$moduleData['moduleTitle']);
    $tpl->parse('main.module_title');

}

/*
 * functii legate de module
 */
function getCurrentModule () {
    global $CURRENT_MODULE;

    if (!isset($CURRENT_MODULE) || $CURRENT_MODULE == '') {
        return false;
    }

    return $CURRENT_MODULE;
}

function setCurrentModule ($getModule = '') {
    global $CURRENT_MODULE;
       $module = "";
        if($getModule != ''){
            $getModule = mysql_real_escape_string($getModule);            
            $query = "SELECT * FROM `modules` WHERE moduleName LIKE '{$getModule}' LIMIT 1";
          
            $result = mysql_query($query);
         
            if(mysql_num_rows($result) == 1){
                $moduleData = mysql_fetch_assoc($result);
                if(trim($moduleData['moduleName']) != ""){                    
                    $CURRENT_MODULE = $moduleData['moduleName'];
                    $module = $moduleData['moduleName'];
                }
            }
        }
            if($module == '' && $getModule != ""){
                $query = "SELECT  * FROM `modules` WHERE moduleUrl LIKE '/{$getModule}/' LIMIT 1";
                $result = mysql_query($query);               
                if(mysql_num_rows($result) == 1){
                    $moduleData = mysql_fetch_assoc($result);
                    $CURRENT_MODULE = $moduleData['moduleName'];
                    $module = $moduleData['moduleName'];
                }
            }
        
    if ($module == '') {
        $module = 'index';
    }
    $CURRENT_MODULE = $module;
}

function getCurrentRequest () {
    global $CURRENT_REQUEST;

    return $CURRENT_REQUEST;
}

function setCurrentRequest ($request = 'default') {
    global $CURRENT_REQUEST;

    $CURRENT_REQUEST = $request;
}

function getCurrentRequestParameters ($var = '') {
    global $CURRENT_REQUEST_PARAMETERS;
    if ($var != '') {
        if (!isset($CURRENT_REQUEST_PARAMETERS[$var])) {
            return '';
        }
        return $CURRENT_REQUEST_PARAMETERS[$var];
    }
    return $CURRENT_REQUEST_PARAMETERS;
}

function setCurrentRequestParameters ($var, $value) {
    global $CURRENT_REQUEST_PARAMETERS;

    if (!isset($CURRENT_REQUEST_PARAMETERS)) {
        $CURRENT_REQUEST_PARAMETERS = array();
    }
    $CURRENT_REQUEST_PARAMETERS[$var] = $value;
}

?>
